package de.wbh.gwt.form.layouter.java.server.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import de.wbh.gwt.form.layouter.java.server.ConfigurationHelper;
import de.wbh.gwt.form.layouter.java.server.PdfToImageConverter;

/**
 * Servlet, welches Dateien auf den Server Uploaded und entweder in das Verzeichnis c:\\webFormLayouter\\pdf oder c:\\webFormLayouter\\efd speichert
 * 
 * @author Jenny
 * 
 */

public class FormFileUploadServlet extends HttpServlet {

	private String UPLOAD_DIRECTORY;

	private final String HOMEDIR = ConfigurationHelper.getInstance().getHomeDirectory();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(req);
			for (FileItem item : items) {
				boolean isPdf = false;
				if (item.isFormField()) {
					continue;
				}
				String fileName = item.getName();
				if (fileName != null) {
					fileName = FilenameUtils.getName(fileName);
				}

				if (fileName.endsWith("pdf") || fileName.endsWith("PDF")) {
					isPdf = true;
					this.UPLOAD_DIRECTORY = this.HOMEDIR + "\\pdf";
				} else {
					this.UPLOAD_DIRECTORY = this.HOMEDIR + "\\efd";
				}
				if (!new File(this.UPLOAD_DIRECTORY).exists()) {
					new File(this.UPLOAD_DIRECTORY).mkdirs();
				}
				File uploadedFile = new File(this.UPLOAD_DIRECTORY, fileName);
				if (uploadedFile.createNewFile()) {
					item.write(uploadedFile);
					resp.setStatus(HttpServletResponse.SC_OK);
					resp.getWriter().print("Datei wurde erfolgreich abgelegt.");
					resp.flushBuffer();
					// Todo pdf in image umwandeln und im Ordner image ablegen , zur Zeit wird immer nur die erste Seite umgewandelt
					if (isPdf) {
						PdfToImageConverter converter = new PdfToImageConverter();
						converter.convert(this.HOMEDIR + "\\image", uploadedFile);
					}
				} else {
					resp.getWriter().print("Die Datei exsistiert schon.");
					resp.setStatus(HttpServletResponse.SC_CONFLICT);
				}
			}
		} catch (Exception e) {
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fehler beim Upload der Datei : " + e.getMessage());
		}
	}
}